﻿using System;
using System.Web;

namespace SystemX.Web
{
    public static partial class Utils
    {
        /// <summary>
        /// 当前应用是否web应用
        /// </summary>
        /// <returns></returns>
        public static bool AppIsRunOnWeb
        {
            get
            {
                return HttpContext.Current != null;
            }
        }
        /// <summary>
        /// 当前应用是web应用，并且可取得session对象
        /// </summary>
        public static bool AppHasWebSession
        {
            get
            {
                return AppIsRunOnWeb && (HttpContext.Current.Session != null);
            }
        }
        /// <summary>
        /// 当前会话是否登录用户的会话
        /// </summary>
        public static bool IsLogined
        {
            get
            {
                return HttpContext.Current.Session["UCUserID"] != null;
            }
        }
        /// <summary>
        /// 当前会话用户ID
        /// </summary>
        public static string CurrentUserID
        {
            get
            {
                if (!IsLogined) return null;
                return HttpContext.Current.Session["UCUserID"].ToString();
            }
        }
        /// <summary>
        /// 获取客户端IP
        /// </summary>
        /// <returns></returns>
        public static string GetClientIP()
        {
            if (!AppIsRunOnWeb) return null;
            string srcIp = HttpContext.Current.Request.Headers["Cdn-Src-Ip"];
            if (string.IsNullOrEmpty(srcIp))
                srcIp = HttpContext.Current.Request.UserHostAddress;

            srcIp = srcIp ?? "";
            return srcIp;
        }

        /// <summary>
        /// 获取当前会话ID
        /// </summary>
        /// <returns></returns>
        public static string GetSessionID()
        {
            if (!AppHasWebSession) return null;
            return HttpContext.Current.Session.SessionID;
        }
        public static object GetSession(string key)
        {
            return HttpContext.Current.Session[key];
        }
        public static void SetSession(string key, object o)
        {
            HttpContext.Current.Session[key] = o;

        }
        public static object GetAppState(string key)
        {
            return HttpContext.Current.Application[key];
        }
        public static void SetAppState(string key, object o)
        {
            HttpContext.Current.Application[key] = o;
        }

		//Cookie
		public static void UpdateCookie(string cookie_name, string cookie_value)
		{
			HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(cookie_name);
			if (cookie == null)
			{
				cookie = new HttpCookie(cookie_name);
				HttpContext.Current.Request.Cookies.Add(cookie);
			}
			cookie.Value = cookie_value;
			HttpContext.Current.Request.Cookies.Set(cookie);
		}
    }
}
